/* Task Notebook
 * Created By: Amanda Rush
 * www.AmandaRush.com
 * DEVELOPMENT ONLY
 */


package com.captainkat.tasknotebook;


import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.content.Intent;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.Date;
import java.util.Calendar;
import java.util.TimeZone;
import java.text.SimpleDateFormat;




import android.net.Uri;
import android.database.Cursor;
import android.content.ContentUris;


//Date Picker
//import android.app.Dialog;
import android.content.DialogInterface;
//import android.app.DatePickerDialog;
//import android.widget.DatePicker;
import android.app.AlertDialog;


//TASKS API THINGS

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.tasks.v1.Tasks;
import com.google.api.services.tasks.v1.model.*;

public class DailyView extends Activity implements OnClickListener {
	protected TextView date;
	protected TextView add;
	protected TextView[] title;
	protected TextView previous;
	protected TextView next;
	protected TextView screen;
	protected Calendar currentDate;
	protected TimeZone timezone;
	protected SimpleDateFormat dateFormat;
	protected SimpleDateFormat timeFormat;
	protected String calendarURI;
	protected String accountToSync;
	protected String accountType;
	protected LinearLayout mainLinearLayout;
	
	//get calendar Uri
	protected Uri calendars;
	//set the calendar 
	protected String calendarId = "-1";
	//for saving default (first) calendar
	protected String defaultCalendarId = "-1";
	//get events uri
	protected Uri eventsUri;
	//gets instances uri
	protected Uri instancesUri;
	//event instances
	//events up to 25
	protected EventHolder[] eventHolder; 
	//calendars up to 10
	protected CalendarHolder[] calendarHolder;
	
	//Date Picker
	static final int DATE_DIALOG_ID = 0;
	
	//New Stuff for Tasks version
	protected AccountManager accountMgr = null;
    
    protected Account[] accounts= null;
    protected AccountManagerFuture[] authtokens =null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//setRequestedOrientation(1);  
		setContentView(R.layout.main);
				
		//get android version
		checkVersion();
			
		
		//set up Views and Click Listeners
		date = (TextView) findViewById(R.id.date);
		date.setOnClickListener(this);
		add = (TextView) findViewById(R.id.add);
		add.setOnClickListener(this);

		//set up title objects???
		mainLinearLayout = (LinearLayout) findViewById(R.id.mainLinearLayout);
		
		previous = (TextView) findViewById(R.id.btnPrevious);
		previous.setOnClickListener(this);
		next = (TextView) findViewById(R.id.btnNext);
		next.setOnClickListener(this);
		
		
		//get today's date on the Calendar
		currentDate = Calendar.getInstance();
		timezone = TimeZone.getDefault();
		currentDate.setTimeZone(timezone);
		dateFormat = new SimpleDateFormat("MM/dd/yyyy");
		timeFormat = new SimpleDateFormat("HH:mm");
		
		
		
		// look for a passed-in date.
		Bundle b;
		if (this.getIntent().getExtras() != null) {
		b = this.getIntent().getExtras();
		currentDate.setTimeInMillis(b.getLong("time"));
		}
		
		//get accounts
	

        super.onCreate(savedInstanceState);
       

        try {
            accountMgr = AccountManager.get(this);
            //get an array of google accounts
            Account [] accounts = accountMgr.getAccountsByType("com.google");
            int i = 0;
            for (Account account: accounts) { //get Auth Tokens for these lovely google accounts
            	authtokens[i] = accountMgr.getAuthToken(account,"goanna_mobile" , null, this, null, null);
            			}

        } catch (Exception e) {
           // setMessage(e.toString());
        	
        }

		
		//get Calendars
		getCalendars();
			
		}
	
	public void checkVersion() {
		if (Integer.parseInt(Build.VERSION.SDK) <=7) //if lower than or equal to Android 2.1
			calendarURI = "calendar";
		else
			calendarURI = "com.android.calendar";
		
		//put in the correct content provider for that version
		calendars = Uri.parse("content://"+calendarURI+"/calendars");
		eventsUri = Uri.parse("content://"+calendarURI+"/events");
		instancesUri = Uri.parse("content://"+calendarURI+"/instances/when");
		
	}
	

	/*public void drawScreen() {
		clearScreen();
		//Build instances uri for ONE DAY STILL NEEDS TIME ZONE?
		Uri.Builder builder = Uri.parse("content://"+calendarURI+"/instances/when").buildUpon();
		long daysofar = ((currentDate.getTimeInMillis()+timezone.getOffset(currentDate.getTimeInMillis())) % DateUtils.DAY_IN_MILLIS);
		long dayleft = DateUtils.DAY_IN_MILLIS - daysofar;
		
		ContentUris.appendId(builder, currentDate.getTimeInMillis() -daysofar  );
		ContentUris.appendId(builder, currentDate.getTimeInMillis() + dayleft  );
		
		//make selection and projection
		String[] projection = new String[] {"calendar_id","event_id", "title","dtstart","dtend"};
		//String selection = "Calendars._id="+calendarId;
		
		Cursor managedCursor = managedQuery(builder.build(), projection,  null,null,"dtstart ASC, dtend ASC");
		
		//iterate and print out to screen
		
		title= new TextView[managedCursor.getCount()];
		eventHolder = new EventHolder[managedCursor.getCount()];
		
		if (managedCursor.moveToFirst()) {
			int c = 0;
			
			int calendarIdColumn = managedCursor.getColumnIndex("calendar_id");
			int titleColumn = managedCursor.getColumnIndex("title");
			int idColumn = managedCursor.getColumnIndex("event_id");
			int startColumn = managedCursor.getColumnIndex("dtstart");
			int endColumn = managedCursor.getColumnIndex("dtend");
			//TODO: CHANGE THIS SO THAT YOU CAN HAVE ACCESS TO YOUR ALLDAY EVENTS
			do {//set up the event
				eventHolder[c] = new EventHolder();
				eventHolder[c].calendarId=managedCursor.getString(calendarIdColumn);
				//get title
				eventHolder[c].title = managedCursor.getString(titleColumn);
				//get id
				eventHolder[c].eid = managedCursor.getString(idColumn);
				
				//get the Times
				eventHolder[c].dtstart = managedCursor.getLong(startColumn);
				eventHolder[c].dtend = managedCursor.getLong(endColumn);
				title[c] = new TextView(mainLinearLayout.getContext());
				//set text on the title
				title[c].setText(timeFormat.format(new Date(eventHolder[c].dtstart))
						+" "+eventHolder[c].title); //edit the title of this textView;
				title[c].setId(c); //set the id so we can click on it and get to the right one!
			
				title[c].setOnClickListener(this); //set up a click listener
				mainLinearLayout.addView(title[c]); //add it to the view
				
				c++;
				
			} while (managedCursor.moveToNext());
		} //end if
	} //end DrawScreen()
	
	*/
	
	public void drawScreen() {
		clearScreen();
		
	//	title= new TextView[];
		
		TaskLists taskLists = Tasks.Tasklists.Get
		
		for (TaskList taskList : taskLists.items) {
		  System.out.println(taskList.title);
		}
		
	} //end DrawScreen()
	
	
	@Override
	public void onClick(View v) {
		
		
		
	switch (v.getId()) { //what to do when you press one of the buttons
		
		//YOU NEED TO PUT THE CLICKERSIN HERE FOR THE TITLES MANNNN
		
			
		case R.id.date:
			//bring the datepicker
			showDialog(DATE_DIALOG_ID);
			
			break;
		case R.id.btnPrevious:
			//change date && reload
			currentDate.add(Calendar.DAY_OF_MONTH, -1);
			//WE NEED TO RELOAD DATA
			drawScreen();
			//edit the intent
			changeIntentTime();
			break;
		case R.id.btnNext:
			//change date && reload
			currentDate.add(Calendar.DAY_OF_MONTH, 1);			
			//WE NEED TO RELOAD DATA
			drawScreen();
			//edit the intent
			changeIntentTime();
			break;
		case R.id.add:
			//set the default calendarId in case they don't select one
			calendarId = defaultCalendarId;
			
			//DIALOG ASKING WHICH CALENDAR!
			//Create the List
			String items[] = new String[calendarHolder.length];
			for (int i = 0; i < calendarHolder.length;i++)
				items[i] = calendarHolder[i].displayName;

			AlertDialog.Builder ab=new AlertDialog.Builder(DailyView.this);
			ab.setTitle("Choose a Calendar");
			
			ab.setSingleChoiceItems(items, -1,  new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface d, int choice) {
				//set the calendar Id equal to the calendar we pick
				calendarId = calendarHolder[choice].calendarId;
			
			}
			});
			ab.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface d, int choice) {
					// on OK button action
					//go on the the add screen
					Intent addAsn = new Intent(DailyView.this, AssignmentEdit.class);
		            Bundle b = new Bundle();
					b.putLong("time",currentDate.getTimeInMillis());
					b.putString("calendarId", calendarId);
					addAsn.putExtras(b);
					startActivity(addAsn);
					finish();
					
					}
					});
			
			ab.show();			
   			break;
   			default: //if it is anything else, it must be an assignment title
   				openEvent(eventHolder[v.getId()],v);
   				break;
   				
			
		}



	}
	
	public void openEvent(EventHolder eventHolder, View v) {
		Intent viewAsn = new Intent(v.getContext(), AssignmentView.class);
		Bundle b = new Bundle();
		b.putLong("time",currentDate.getTimeInMillis());
		b.putString("calendarId", eventHolder.calendarId);
		b.putString("eid",eventHolder.eid);
		viewAsn.putExtras(b);
        startActivity(viewAsn);
        finish();
		}
	
	
	public void clearScreen() {
		//clear the Assignments
		try { 
		for (int i =0; i<title.length; i++)
			mainLinearLayout.removeView(title[i]);
			
		} catch (NullPointerException e) {
			//Must have already been clear!
			//It's okay to do nothing at all here.
		}
		
		date.setText(dateFormat.format(currentDate.getTime()));
		
		}

	
	public void getCalendars() {
		//TODO: FIX CALENDAR HOLDER
		//look for calendars... 
		try { //in case no databases exists
		String[] projection = new String[] {"_id", "name","displayName"};
		Cursor managedCursor = managedQuery(calendars, projection, "selected=1", null, null);
		calendarHolder = new CalendarHolder[managedCursor.getCount()];
		if (managedCursor.moveToFirst()) { //if we found a calendar, find the rest
			int c = 0;
			
			int nameColumn = managedCursor.getColumnIndex("name");
			int idColumn = managedCursor.getColumnIndex("_id");
			int dispColumn = managedCursor.getColumnIndex("displayName");
			do {
				calendarHolder[c] = new CalendarHolder();
				calendarHolder[c].name = managedCursor.getString(nameColumn);
				calendarHolder[c].calendarId = managedCursor.getString(idColumn);
				calendarHolder[c].displayName = managedCursor.getString(dispColumn);
				
				if (c== 0) {
					//Save the first calendar id as default
					defaultCalendarId = calendarHolder[c].calendarId;
					}
				
				c++;
			} while (managedCursor.moveToNext());
			
			//draw the screen
			drawScreen();
		}
			
		} catch (NullPointerException e) { //In case we don't have access to the database
			clearScreen();
			//You do not have access to calendars, and this app will not work for you
			//title[0].setText("You do not have access to Android calendar. Please ensure that it is available on your device.");
			//Disable Buttons
			//title[1].setText("Devices that are not Google licensed are not supported.");
			//for (int i = 0; i<25; i++)
			//	title[i].setEnabled(false);
			previous.setEnabled(false);
			next.setEnabled(false);
			add.setEnabled(false);
			date.setEnabled(false);
		} 
	
	}
	
	//DATE PICKER THINGS
	// Creating dialog


	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
	// onDateSet method
	public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
		//String date_selected = String.valueOf(monthOfYear)+"/"+String.valueOf(dayOfMonth)+"/"+String.valueOf(year);
		
		currentDate.set(Calendar.MONTH, monthOfYear);
		currentDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
		currentDate.set(Calendar.YEAR, year);
		
	//show the date on the screen
		date.setText(dateFormat.format(currentDate.getTime()));
		
		changeIntentTime();
		//WE NEED TO RELOAD DATA
		drawScreen();
		
	}
	};
	
	@Override
	protected Dialog onCreateDialog(int id) {
	
	int cyear = currentDate.get(Calendar.YEAR);
	int cmonth = currentDate.get(Calendar.MONTH);
	int cday = currentDate.get(Calendar.DAY_OF_MONTH);
	switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener,  cyear, cmonth, cday);
				}
	return null;
	}
	
	public void changeIntentTime() {
		//edit the intent
		Bundle b = new Bundle();
		b.putLong("time", currentDate.getTimeInMillis());
		this.getIntent().replaceExtras(b);
	}
}
